import UserCenter from './user.js'
import $util from './util.js';
import permission from "./permission.js"
import * as amapFile from "./amap-wx.130.js"
class tool { 
	constructor() {}
}

//let apiUrl = 'http://www.api.co/';
let apiUrl = 'https://dev.bigcc.net.cn/';
tool.apiurl = apiUrl + 'api/';
tool.imgurl = apiUrl;
tool.host   = apiUrl;

function get_img(path, size = 0, os = 1) { //size 图片需要返回的大小，os是否上传到了oss
	if (path == "" || !path) {
		return tool.host + 'uploads/avatar.jpg';
	}  
	if (path.indexOf('http') == -1 && path.indexOf('file') == -1) {
		if (os <= 0) { 
			return tool.host + path;
		}
		if (size <= 0) {
			return tool.imgurl + path;
		}
		return tool.imgurl + path + "?x-oss-process=style/width" + size;
	}
	if (path.indexOf('alicdn') != -1 && size > 0) {
		return path + '_' + size + 'x' + size + '.jpg';
	}
	
	if (path.indexOf('360buyimg') != -1 && path.indexOf('/jfs/') != -1 && size > 0) {
		return path.replace("/jfs/","/s"+size+"x"+size+"_jfs/");
	}
	
	return path;
}

function openwin(page = "", p = {}) {

	if (page.indexOf("http") != -1) {
		uni.navigateTo({
			url: '/pages/jump/jump',
			success: function(res) {
			// 通过eventChannel向被打开页面传送数据
			res.eventChannel.emit('thisJumpLinks',page)
			}
		});
		return;
	}
	
	setTimeout(()=>{
	// #ifndef H5
	//getApp().globalData.clicklog.push(page);
	// #endif
	},1000)
	
	let url = page + '?pageprame=' + JSON.stringify(p);
	if (page.indexOf("?") != -1) {
		url = page + '&pageprame=' + JSON.stringify(p);
	}
	uni.navigateTo({
		url: url,
		fail(e) {
			console.log(e,'打开窗口失败的')
			if(e.errMsg && e.errMsg !='' && e.errMsg.indexOf('not found') != -1){
			$util.toast('打开页面失败')
			}
		}
	});
} 
function dealRich(html,color = '#383838',size = '16px') {
	if (html == "" || !html || typeof html == "undefined") {
		return
	}
	let newContent= html.replace(/<img[^>]*>/gi,function(match,capture){
	  match = match.replace(/style="[^"]+"/gi, '').replace(/style='[^']+'/gi, '');
	  match = match.replace(/width="[^"]+"/gi, '').replace(/width='[^']+'/gi, '');
	  match = match.replace(/height="[^"]+"/gi, '').replace(/height='[^']+'/gi, '');
	  return match;
	});
	
	newContent = newContent.replace(/<p/gi, '<p style="font-size: '+size+'; line-height:25px;color:'+color+'"').replace(/<p/gi, '<p style="font-size: '+size+'; line-height:25px;"');
	newContent = newContent.replace(/<span/gi, '<p style="font-size: '+size+'; line-height:25px;color:'+color+'"').replace(/<p/gi, '<p style="font-size: '+size+'; line-height:25px;"');
	 
	newContent = newContent.replace(/style="[^"]+"/gi,function(match,capture){
	  match = match.replace(/width:[^;]+;/gi, 'max-width:100%;').replace(/width:[^;]+;/gi, 'max-width:100%;');
	  return match;
	});
	newContent = newContent.replace(/<br[^>]*\/>/gi, '');
	newContent = newContent.replace(/\<img/gi, '<img style="max-width:100%;height:auto;display:block;margin-top:0;margin-bottom:0;"');
	return newContent;
}

function getlocation(callback){
	// #ifdef APP
	permission.request({
		id: 'location',
		name: '位置信息'
	}, (res) => {
		if (res) {
			getlocation_(callback);
		}
	},'获取您附近产品/商家，需获取您位置信息，请您允许');
	return
	// #endif
	
	// #ifdef APP || H5
	getlocation_(callback);
	// #endif
	
	// #ifdef MP
	getlocation_wx(callback);
	// #endif
	
}

function getlocation_(callback){
	console.log('h5dingwei')
	uni.getLocation({
		type: 'gcj02',
		success: function (res) {
			console.log('当前位置的经度：' + res.longitude);
			console.log('当前位置的纬度：' + res.latitude);
			$util.ajax({
				url:'https://restapi.amap.com/v3/geocode/regeo?parameters&key=8b81e49bd6f4d6506493b305d699a31d&location='+res.longitude+','+res.latitude
			},(r,e)=>{
				console.log(r)
				if(r.status == 1 || r.status == '1'){
					let d = r.regeocode.addressComponent
					callback({code:1,prame:{province:d.province,city:d.city,district:d.district,township:d.township,lon:res.longitude,lat:res.latitude},local:{lon:res.longitude,lat:res.latitude}})
					return
				}
				callback({code:0})
			})
		},
		fail(err) {
		console.log('定位失败....',JSON.stringify(err))	
		}
	})
}

function getlocation_wx_(callback){
	console.log('开始定位了')
	//var amapFile = require('./amap-wxx.130.js');//如：..­/..­/libs/amap-wx.js
	const amapObject = new amapFile.AMapWX({ key: '217481bd5dd26778de592a93bcb78f09' })
	amapObject.getRegeo({
		success: (res) => {
		    console.log(JSON.stringify(res))
			if(res && res[0] && res[0].regeocodeData && res[0].regeocodeData.addressComponent){
				let ds = res[0]
				let d = res[0].regeocodeData.addressComponent
				callback({code:1,prame:{province:d.province,city:d.city,district:d.district,township:d.township,lon:ds.longitude,lat:ds.latitude},local:{lon:ds.longitude,lat:ds.latitude}})
				return
			}
			callback({code:0})
			
			return
			$util.ajax({
				url:'https://restapi.amap.com/v3/geocode/regeo?parameters&key=47e5281efc4b38b9dfa32f4a8624894f&location='+ds.longitude+','+ds.latitude+'&s=rsx&sdkversion=sdkversion&logversion=logversion'
			},(r,e)=>{
				console.log('dddddddddddddddddddddd',r)
				
				if(r.status == 1 || r.status == '1'){
					let d = r.regeocode.addressComponent
					callback({code:1,prame:{province:d.province,city:d.city,district:d.district,township:d.township,lon:ds.longitude,lat:ds.latitude},local:{lon:ds.longitude,lat:ds.latitude}})
					return
				}
				callback({code:0})
			})
		},
		fail: (err) => {
			console.log('定位失败了',JSON.stringify(err))
			callback({code:0})
		}
	})
}
	function getlocation_wx(callback){
	  let that = this
	  wx.getSetting({
	    success: (res) => {
	      let authSetting = res.authSetting
		  console.log(JSON.stringify(authSetting))
	      if (authSetting['scope.userLocation']) {
	        getlocation_wx_(callback)
	      } else if (authSetting['scope.userLocation'] === false) {
	        wx.showModal({
	          title: '您未开启地理位置授权',
	          content: '请在系统设置中打开位置授权，以便我们为您提供更好的服务!',
	          success: (res) => {
	            if (res.confirm) {
	              wx.openSetting()
	            }
	          }
	        })
	      } else {
	        wx.authorize({
	          scope: 'scope.userLocation',
	          success: (res) => {
	            getlocation_wx_(callback)
	          },
	          fail: (err) => {
				  console.log('dingweierr',JSON.stringify(err))
	            wx.showModal({
	              title: '您未开启地理位置授权',
	              content: '请在系统设置中打开位置授权，以便我们为您提供更好的服务!',
	              success: (res) => {
	                if (res.confirm) {
	                  wx.openSetting()
	                }
	              }
	            })
	          }
	        })
	      }
	    }
	  })
	}

function sendmsg(data = {}, num = 0){
		data.stock_userid = UserCenter.getUserInfo().id;
		//data.apitoken = UserCenter.getUserInfo().apitoken;
		// #ifdef H5
		data.comefrom = "H5"
		// #endif
		// #ifdef APP
		data.comefrom = "app"
		// #endif
		// #ifdef MP
		data.comefrom = "wxapp"
		// #endif

		data.timestamp = parseInt(Date.now() / 1e3);
		//如果是命令
		//if(data.stock_type && data.stock_type == 'command' && !data.stock_name){
		//	data.stock_name = data.url
		//}
		//没有连接成功就把发送加入列队
		if(!getApp().globalData.websocket && data.stock_type != 'close' && data.stock_type != 'pong' && data.stock_type != 'bindlogin' &&  data.stock_type != 'Index/gettsmsg'){
			let has = false;
			let rr = getApp().globalData.socketlist;
			for (var i = 0; i < rr.length; i++) {
				if(JSON.stringify(rr[i]) == JSON.stringify(data)){
					has = true
				}
			}
			if(!has){
			getApp().globalData.socketlist.push(data);
			console.log('链接未上线缓存到列队',JSON.stringify(data))
			}
			$util.sendEvent('sendErr')
			if(data.stock_type=='chatSay')
			$util.toast('网络问题发送失败，请重启app')
			return
		}
		console.log(JSON.stringify(data))
		uni.sendSocketMessage({
			data: JSON.stringify(data),
			success:(res)=>{
				//getApp().globalData.websocket = true
			},
			fail: (err) => {
				getApp().globalData.websocket = false
				$util.sendEvent('sendErr')
				//重新请求机制
				if (num <= 3 && data.stocktype == 'command') {
					setTimeout(() => {
						this.sendmsg(data, num++)
					}, 2000)
				}
				if (data.tsmsg) {
					$util.toast('网络遇到问题，正在重连')
				}
			},
			complete: (res) => {
				//console.log('发送回调' + JSON.stringify(res))
			}
		});
	}

export {
	tool,
	get_img,
	openwin,
	dealRich,
	getlocation,
	sendmsg
};
